<template>
  <div class="app-container">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="search-form">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入角色编码" clearable style="width: 240px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb-3">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" :icon="Delete" :disabled="selectedIds.length === 0" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
      </el-row>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="角色编号" prop="id" width="100" align="center" />
        <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="角色编码" prop="code" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="sort" width="100" align="center" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <dict-tag dict-type="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" width="160">
          <template #default="scope">
            <span>{{ formatDateTime(scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="primary" link :icon="Setting" @click="handlePermission(scope.row)">权限</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-if="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="roleFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <dict-radio
            v-model="form.status"
            dict-type="sys_normal_disable"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" v-model="permDialog.visible" width="500px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="permDialog.roleName" disabled />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="permTreeRef"
            :data="permDialog.menuOptions"
            :props="{ label: 'name', children: 'children' }"
            show-checkbox
            node-key="id"
            default-expand-all
            :default-checked-keys="permDialog.checkedMenuIds"
            :check-strictly="true"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPermission">确 定</el-button>
          <el-button @click="permDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { 
  getRoleList, 
  getRoleDetail, 
  createRole, 
  updateRole, 
  deleteRole, 
  updateRoleStatus,
  getRolePermissions,
  assignRolePermissions
} from '@/api/role'
import { getMenuTree } from '@/api/menu'
import Pagination from '@/components/Pagination/index.vue'
import useDict from '@/hooks/useDict'

// 状态数据字典
const statusOptions = [
  { value: 1, label: '正常' },
  { value: 0, label: '停用' }
]

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  name: '',
  code: '',
  status: null
})

// 日期范围
const dateRange = ref([])

// 表格数据
const roleList = ref([])
const loading = ref(false)
const total = ref(0)
const selectedIds = ref([])
const queryFormRef = ref(null)
const roleFormRef = ref(null)
const permTreeRef = ref(null)

// 表单参数
const form = reactive({
  id: null,
  name: '',
  code: '',
  sort: 0,
  status: 1,
  remark: ''
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '角色名称长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '角色编码不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '角色编码长度必须介于 2 和 20 之间', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '排序不能为空', trigger: 'blur' }
  ]
}

// 角色表单对话框
const dialog = reactive({
  title: '',
  visible: false
})

// 权限分配对话框
const permDialog = reactive({
  visible: false,
  roleId: null,
  roleName: '',
  menuOptions: [],
  checkedMenuIds: []
})

// 字典数据
const { dicts } = useDict('sys_normal_disable')

// 格式化日期时间
const formatDateTime = (value) => {
  if (!value) return ''
  return new Date(value).toLocaleString()
}

// 获取角色列表
const getList = async () => {
  loading.value = true
  try {
    // 处理日期范围
    const params = { ...queryParams }
    if (dateRange.value && dateRange.value.length === 2) {
      params.beginTime = dateRange.value[0]
      params.endTime = dateRange.value[1]
    }
    
    const res = await getRoleList(params)
    roleList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取菜单树
const getMenuTreeData = async () => {
  try {
    const res = await getMenuTree()
    permDialog.menuOptions = res.data
  } catch (error) {
    console.error('获取菜单树失败:', error)
    ElMessage.error('获取菜单树失败')
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 表单重置
const resetForm = () => {
  roleFormRef.value?.resetFields()
  Object.assign(form, {
    id: null,
    name: '',
    code: '',
    sort: 0,
    status: 1,
    remark: ''
  })
}

// 状态修改
const handleStatusChange = async (row) => {
  try {
    await updateRoleStatus(row.id, row.status)
    ElMessage.success(`修改角色状态成功`)
  } catch (error) {
    console.error('修改角色状态失败:', error)
    ElMessage.error('修改角色状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 新增按钮操作
const handleAdd = () => {
  resetForm()
  dialog.title = '添加角色'
  dialog.visible = true
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  dialog.title = '修改角色'
  dialog.visible = true
  
  try {
    const res = await getRoleDetail(row.id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 提交表单
const submitForm = () => {
  roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (form.id) {
          // 修改
          await updateRole(form.id, form)
          ElMessage.success('修改角色成功')
        } else {
          // 新增
          await createRole(form)
          ElMessage.success('新增角色成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error(form.id ? '修改角色失败:' : '新增角色失败:', error)
        ElMessage.error(form.id ? '修改角色失败' : '新增角色失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除角色"${row.name}"吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 批量删除操作
const handleBatchDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的${selectedIds.value.length}个角色吗?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 逐个删除选中的角色
      await Promise.all(selectedIds.value.map(id => deleteRole(id)))
      ElMessage.success('批量删除成功')
      getList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 权限按钮操作
const handlePermission = async (row) => {
  permDialog.roleId = row.id
  permDialog.roleName = row.name
  permDialog.visible = true
  permDialog.checkedMenuIds = []

  try {
    // 获取角色已分配的权限
    const res = await getRolePermissions(row.id)
    permDialog.checkedMenuIds = res.data
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 提交权限
const submitPermission = async () => {
  const menuIds = permTreeRef.value.getCheckedKeys()
  
  try {
    await assignRolePermissions(permDialog.roleId, menuIds)
    ElMessage.success('分配权限成功')
    permDialog.visible = false
  } catch (error) {
    console.error('分配权限失败:', error)
    ElMessage.error('分配权限失败')
  }
}

onMounted(() => {
  getList()
  getMenuTreeData()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
}

.mb-3 {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 